package com.echat.ebluetooth.protocol.code;


import com.echat.ebluetooth.bean.Beacon;
import com.echat.ebluetooth.protocol.entity.BusinessData;
import com.echat.ebluetooth.protocol.entity.PackageData;
import com.echat.ebluetooth.util.ArraysUtils;
import com.echat.ebluetooth.util.BitOperator;

public class MsgEncoder {

    /**
     * 编码包数据
     *
     * @param data
     * @return
     */
    public static byte[] encodePackageData(PackageData data) {
        byte[] dataBody = new byte[36 + data.getBusinessData().length];
        ArraysUtils.arrayappend(dataBody, 0, BitOperator.integerTo2Bytes(data.getType()));
        ArraysUtils.arrayappend(dataBody, 2, BitOperator.integerTo1Bytes((20 + data.getBusinessData().length)));
        dataBody[3] = 0;
        ArraysUtils.arrayappend(dataBody, 4, BitOperator.hexStringToBytes(data.getSourceAddress()));
        ArraysUtils.arrayappend(dataBody, 8, BitOperator.hexStringToBytes(data.getDestinationAddress()));
        dataBody[12] = data.getProtocolVer();
        dataBody[13] = data.getDataType();
        ArraysUtils.arrayappend(dataBody, 14, BitOperator.integerTo2Bytes(data.getPacketOrder()));
        ArraysUtils.arrayappend(dataBody, 16, BitOperator.longToBytes(data.getSysTimer(), 4));
        ArraysUtils.arrayappend(dataBody, 20, BitOperator.hexStringToBytes(data.getUcMac()));
        ArraysUtils.arrayappend(dataBody, 30, BitOperator.integerTo2Bytes(data.getReserve()));
        ArraysUtils.arrayappend(dataBody, 32, data.getBusinessData());
        ArraysUtils.arrayappend(dataBody, 32 + data.getBusinessData().length, new byte[2]);
        ArraysUtils.arrayappend(dataBody, 34 + data.getBusinessData().length, BitOperator.integerTo2Bytes(data.getEndByte()));
        return dataBody;
    }


    /**
     * 编码业务数据
     *
     * @param data
     * @return
     */
    public static byte[] encodeBusinessData(BusinessData data) {
        byte[] bodyBytes = new byte[3 + data.getBeaconList().size() * 3];
        ArraysUtils.arrayappend(bodyBytes, 0, BitOperator.integerTo2Bytes(data.getAccount()));
        ArraysUtils.arrayappend(bodyBytes, 2, BitOperator.integerTo1Bytes(data.getState()));
        for (int i = 0; i < data.getBeaconList().size(); i++) {
            Beacon beacon = data.getBeaconList().get(i);
            String address = BitOperator.deleteCharString(beacon.getAddress(), ':');
            String afterFour = address.substring(address.length() - 4, address.length());
            byte[] beaconBytes = BitOperator.concatAll(
                    BitOperator.integerTo2Bytes(Integer.parseInt(afterFour, 16)),
                    BitOperator.integerTo1Bytes(beacon.getRssi() + 94));
            ArraysUtils.arrayappend(bodyBytes, 3 + i * 3, beaconBytes);
        }
        return BitOperator.concatAll(
                BitOperator.integerTo1Bytes(data.getPkgHead()),
                BitOperator.integerTo1Bytes(bodyBytes.length),
                bodyBytes);
    }
}
